package cn.schoolwow.quickdao.module.database.ddl.query.flow.index.getSingleEntityIndexFlow;

import cn.schoolwow.quickdao.annotation.IndexType;
import cn.schoolwow.quickdao.domain.database.ddl.IndexField;
import cn.schoolwow.quickdao.module.database.parent.domain.ResultSetConsumer;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.sql.ResultSet;
import java.util.Arrays;

public class GetSingleEntityIndexBySQLServerFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String tableName = (String) flowContext.checkData("tableName");
        String indexName = (String) flowContext.checkData("indexName");
        flowContext.startFlow(new ExecuteQueryConnectionFlow())
                .putTemporaryData("sql", "select i.is_unique,i.name,col.name col_name from sys.indexes i left join sys.index_columns ic on ic.object_id = i.object_id and ic.index_id = i.index_id left join (select * from sys.all_columns where object_id = object_id(?, N'U' )) col on ic.column_id = col.column_id where i.object_id = object_id(?, N'U' ) and i.index_id > 0 and i.name = ?;")
                .putTemporaryData("parameters", Arrays.asList(tableName, tableName, indexName))
                .putReturnData("resultSetConsumer",new ResultSetConsumer() {
                    @Override
                    public void consumeResultSet(ResultSet resultSet) throws Exception {
                        IndexField indexField = null;
                        while(resultSet.next()){
                            if(null==indexField){
                                indexField = new IndexField();
                                if (resultSet.getBoolean("is_unique")) {
                                    indexField.indexType = IndexType.UNIQUE;
                                } else {
                                    indexField.indexType = IndexType.NORMAL;
                                }
                                indexField.indexName = resultSet.getString("name");
                                indexField.columns.add(resultSet.getNString("col_name"));
                            }else{
                                indexField.columns.add(resultSet.getNString("col_name"));
                            }
                        }
                        flowContext.putData("indexField", indexField);
                    }
                })
                .execute();
    }

    @Override
    public String name() {
        return "获取数据库单个表的索引信息-SQLServer";
    }
}
